package com.wontube.core.conf.dogs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.wontube.client.extension.utils.FileUtils;
import com.wontube.core.conf.Cron;
import com.wontube.core.cron.JobsManager;
import com.wontube.core.srv.ServiceManager;
import com.wontube.core.srv.schedule.IScheduleService;



/**
 * @author yuechao
 *
 */
public final class CronWatchDog extends FileWatchDog {
	private static final Logger logger = LoggerFactory.getLogger(CronWatchDog.class);
	private List<Cron> listCron = new ArrayList<Cron>();

	public CronWatchDog(String confPath) {
		super(confPath);
	}

	/* 
	 * @see core.pub.FileWatchDog#doOnChange()
	 */
	@Override
	protected void doOnChange() {
		String[] lines = new String[0]; 
		try {
			lines = FileUtils.readAllLines(super.file);
		} catch (IOException e) {
			logger.error(e.toString());
		}
		
		if (lines.length < 1) {
			return;
		}
		
		IScheduleService service = ServiceManager.get(IScheduleService.class);
		if (service == null) {
			return;
		}
		
		logger.info("begin to load cron tables");

		for (Cron cron : this.listCron) {
			service.removeTask(cron);
		}
		
		this.listCron.clear();
		
		for (String line : lines) {
			String text = line.trim();
			
			if ("".equals(text) || text.startsWith("#")) {
				continue;
			}
			
			Cron cron = new Cron();
			if (cron.parse(text)) {
				if (!JobsManager.isCommandSupported(cron.getCommand())) {
					logger.warn("command {} is not supported, ignored.", cron.getCommand());
					continue;
				}
				
				listCron.add(cron);
				service.schedule(cron);
			}
		}
		
		logger.info("finished loading cron tables, count = {}", this.listCron.size());
	}


	@Override
	protected String getFilename() {
		return "crontab.conf";
	}
}
